package net.alche.fa.core.doing.invoker;

import net.alche.fa.core.model.FaValue;
import net.alche.fa.core.FaPlatform;
import java.util.List;
import net.alche.fa.core.FaException;
import net.alche.fa.core.FaClass;
import java.util.Map;
import net.alche.al.util.AC;
import java.util.ArrayList;

// FatInvokerUtil
@SuppressWarnings("all") 
public class FatInvokerUtil {

  public FatInvokerUtil() {}

  public static FaValue fatDo(FaPlatform plat, FaValue objVal, String methodName, List<FaValue> params ) throws FaException {
    switch ( methodName) {
      case "getJsonList" : {
        return getJsonList(plat, params);
      }
      case "getJsonObj" : {
        return getJsonObj(plat, params);
      }
      case "toJsonStr" : {
        return toJsonStr(plat, params);
      }
    }
    return new FaValue();
  }

  public static FaValue getJsonList(FaPlatform plat, List<FaValue> params) throws FaException {
    String json = params.get(0).getStrValue();
    String clas = params.get(1).getStrValue();
    Object obj = params.get(1).getObjValue();
    if ( obj != null && obj instanceof FaClass) {
      FaClass fc = (FaClass)obj;
      clas = fc.getConf().getName();
    }
    FaValue fav = new FaValue();
    fav.setType(FaValue._LIST);
    fav.setObjType("List<" + clas + ">");
    List<Map> list = AC.json.getMapList(json);
    if ( list != null && !list.isEmpty()) {
      fav.setNull(false);
      List<FaValue> favList = new ArrayList<> ();
      fav.setObjValue(favList);
      for ( Map map: list) {
        try {
          FaValue val = FaValue.mapToPojo(plat, map , clas , null);
          favList.add(val);
        }
        catch ( Exception ex) {
          ex.printStackTrace();
        }
      }
    }
    return fav;
  }

  public static FaValue getJsonObj(FaPlatform plat, List<FaValue> params) throws FaException {
    String json = params.get(0).getStrValue();
    String clas = params.get(1).getStrValue();
    Object obj = params.get(1).getObjValue();
    if ( obj != null && obj instanceof FaClass) {
      FaClass fc = (FaClass)obj;
      clas = fc.getConf().getName();
    }
    Map map = AC.json.getMap(json);
    FaValue val = FaValue.mapToPojo(plat, map , clas , null);
    return val;
  }

  public static FaValue toJsonStr(FaPlatform plat, List<FaValue> params) {
    FaValue val = new FaValue();
    val.setType(FaValue._STRING);
    FaValue par = params.get(0);
    if ( !par.isNull()) {
      if ( par.getSageValue() != null) {}
      // Map<String,Object> jsonMap=new 
      // Map<String,FaValue> map = par.getSageValue().getVars()
      // for Entry<String,FaValue> item: map.entrySet()
      //   
      else {
        val.setNull(false);
        val.setStrValue(AC.json.toStr(par.getValue()));
      }
    }
    return val;
  }
}